package com.cy.pj.goods.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao{
    @Autowired
    private DataSource dataSource;
//
    Map<String,Object> rowMap(ResultSetMetaData rsmd,ResultSet rs) throws SQLException {
        HashMap<String, Object> map = new HashMap<>();
        for (int i=1;i<=rsmd.getColumnCount();i++){
            map.put(rsmd.getColumnName(i),rs.getObject(rsmd.getColumnName(i)));
        }
        return map;
    }

    private static final Logger log = LoggerFactory.getLogger(DefaultGoodsDao.class);

    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";

        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);

            ResultSetMetaData rsmd = rs.getMetaData();
            List<Map<String,Object>> list = new ArrayList<>();
            while (rs.next()){
//                HashMap<String, Object> map = new HashMap<>();
//                map.put("id", rs.getInt("id"));
//                map.put("name", rs.getString("name"));
//                map.put("remark", rs.getString("remark"));
//                map.put("createdTimme", rs.getTimestamp("createdTime"));
//                list.add(map);
                list.add(rowMap(rsmd, rs));
            }
            return list;
        }catch (Exception a){
            a.printStackTrace();
            log.error("查询异常,{}"+a.getMessage());
            return null;
        }finally {
            if(rs!=null)try{rs.close();}catch (Exception a){a.printStackTrace();}
            if(stmt!=null)try{stmt.close();}catch (Exception a){a.printStackTrace();}
            if(conn!=null)try{conn.close();}catch (Exception a){a.printStackTrace();}
        }
    }
}
